package com.example.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lbq
 * @version 1.0
 * @date 2021/6/27 20:17
 */
@Configuration
public class RabbitmqConfig {

    // rabbitmq交换机
    public static final String ORDER_STATUS_EXCHANGE = "order.status.exchange";
    public static final String DEAD_ORDER_STATUS_EXCHANGE = "dead.order.status.exchange";

    // rabbitmq routingkey
    public static final String ORDER_STATUS_QUEUE_ROUTING_KEY = "order.status.routingkey";
    public static final String DEAD_ORDER_STATUS_QUEUE_ROUTING_KEY = "dead.order.status.routingkey";

    // rabbitmq队列
    public static final String ORDER_STATUS_QUEUE_NAME = "order.status.queue";
    public static final String DEAD_ORDER_STATUS_QUEUE_NAME = "dead.order.status.queue";

    // 声明订单状态检查交换机Exchange
    @Bean("orderStatusExchange")
    public DirectExchange orderStatusExchange() {
        return new DirectExchange(ORDER_STATUS_EXCHANGE);
    }

    // 声明死信交换机Exchange
    @Bean("deadOrderStatusExchange")
    public DirectExchange deadOrderStatusExchange() {
        return new DirectExchange(DEAD_ORDER_STATUS_EXCHANGE);
    }

    // 声明订单状态检查队列
    @Bean("orderStatusQueue")
    public Queue orderStatusQueue() {

        Map<String, Object> args = new HashMap<>(4);
        // x-message-ttl    这里声明当前队列消息过期时间
        args.put("x-message-ttl", 20_000);
        // x-dead-letter-exchange    这里声明当前队列绑定的死信交换机
        args.put("x-dead-letter-exchange", DEAD_ORDER_STATUS_EXCHANGE);
        // x-dead-letter-routing-key  这里声明当前队列的死信路由key
        args.put("x-dead-letter-routing-key", DEAD_ORDER_STATUS_QUEUE_ROUTING_KEY);

        return QueueBuilder.durable(ORDER_STATUS_QUEUE_NAME).withArguments(args).build();
    }

    // 声明死信队列
    @Bean("deadOrderStatusQueue")
    public Queue deadOrderStatusQueue() {
        return new Queue(DEAD_ORDER_STATUS_QUEUE_NAME);
    }

    // 声明订单状态检查队列绑定到订单状态检查交换机
    @Bean
    public Binding businessBindingA(@Qualifier("orderStatusQueue") Queue queue,
                                    @Qualifier("orderStatusExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(ORDER_STATUS_QUEUE_ROUTING_KEY);
    }

    // 声明死信队列绑定到死信交换机
    @Bean
    public Binding deadBindingA(@Qualifier("deadOrderStatusQueue") Queue queue,
                                @Qualifier("deadOrderStatusExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(DEAD_ORDER_STATUS_QUEUE_ROUTING_KEY);
    }
}
